﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Net.Cache;
using System.Web.Caching;
using System.Globalization;
using DDNY.WebPortals.Common;
using System.Net;
using System.IO;
using System.Reflection;
using System.Xml.XPath;


/// <summary>
/// Summary description for GoogleHelper
/// </summary>
public class GoogleHelper
{
  public const string GoogleFinanceFeedUrl = "http://finance.google.com/finance?morenews=10&rating=1&q={0}&output=rss";

  public const string GoogleNewsFeedUrl = "http://news.google.com/news?svnum=7&as_scoring=r&client=firefox-a&tab=wn&hl=en&ned=us&aq=f&q={0}&ie=UTF-8&nolr=1&output=rss";

  public const string GoogleNewsFeedUrlAtom = "http://news.google.com/news?hl=en&ned=us&q={0}&ie=UTF-8&nolr=1&output=atom";

  public const string BlogSearchFeedUrl = "http://www.google.com/search?q={0}+-blogspot.com&hl=en&tbm=blg&num=100&output=rss";

  private const string TrendsCacheKey = "TrendsCacheKey";

  public static List<string> GetTrendWords()
  {

    Cache cache = HttpContext.Current.Cache;
    List<string> result = null;
    if (cache[TrendsCacheKey] == null)
    {
      result = LoadRangeOfTrendWords(0, 99);
      cache.Add(TrendsCacheKey, result, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

    }
    else
    {
      result = cache[TrendsCacheKey] as List<string>;
    }
    return result;
  }


  public static List<string> LoadRangeOfTrendWords(int from, int to)
  {
    List<string> words = new List<string>();
    List<string> allwords = LoadTrendWords();
    if (to > allwords.Count - 1)
    {
      to = allwords.Count - 1;
    }
    if (from > allwords.Count - 1)
    {
      from = 0;
    }
    for (int i = from; i < to; i++)
    {
      string wordItem = allwords[i];
      words.Add(wordItem);
    }

    return words;
  }

  private static bool GetRandomBool(int percentage, int maxNumber)
  {
    Random rand = new Random();
    bool result;
    double nextDouble = rand.NextDouble();
    double testDouble = Convert.ToDouble(percentage) / maxNumber;
    result = nextDouble > testDouble;
    return result;

  }

  public static List<string> LoadTrendWords()
  {
    Cache cache = HttpContext.Current.Cache;
    List<string> result = new List<string>();
    XmlDocument doc = new XmlDocument();
    doc.Load("http://google.com/trends/hottrends/atom/hourly");
    Regex regex = new Regex(@"<a.*href=[""'](?<url>[^""^']+[.]*)[""'].*>(?<name>[^<]+[.]*)</a>");
    foreach (XmlNode item in doc.ChildNodes)
    {
      MatchCollection matches = regex.Matches(item.InnerText);
      foreach (Match matchItem in matches)
      {
        string keyword = matchItem.Groups["name"].Value;


        bool IsKeyWordAllowed = CheckKeyWordAllowed(keyword);
        if (IsKeyWordAllowed)
        {
          TextInfo UsaTextInfo = new CultureInfo("en-US", false).TextInfo;

          string capitalized = UsaTextInfo.ToTitleCase(keyword);
          result.Add(capitalized);
          AddToTrendsArchive(capitalized);
        }
      }
    }
    return result;
  }

  public static void AddToTrendsArchive(string capitalized)
  {
    try
    {
      Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
      //XPathDocument xpathDoc = new XPathDocument(new FileStream("TrendWords.xml", FileMode.OpenOrCreate));
      XmlDocument doc = new XmlDocument();
      doc.Load("TrendWords.xml");
      //XPathNavigator navigator = xpathDoc.CreateNavigator();
      XmlNode nodeToAdd = doc.SelectSingleNode("//trend[@keyword='" + capitalized + "']");
      if (nodeToAdd == null)
      {
        nodeToAdd = doc.CreateNode("element", "trend", null);
        XmlAttribute keywordAttribute = doc.CreateAttribute("keyword");
        keywordAttribute.Value = capitalized;
        XmlAttribute lastseenAttribute = doc.CreateAttribute("lastseen");

        lastseenAttribute.Value = DateTime.Now.ToString("dd.MM.yyyy HH:mm");
        XmlAttribute firstseenAttribute = doc.CreateAttribute("firstseen");
        firstseenAttribute.Value = DateTime.Now.ToString("dd.MM.yyyy HH:mm");
        XmlAttribute timesseenAttribute = doc.CreateAttribute("timesseen");
        timesseenAttribute.Value = "1";

        nodeToAdd.Attributes.Append(keywordAttribute);
        nodeToAdd.Attributes.Append(firstseenAttribute);
        nodeToAdd.Attributes.Append(lastseenAttribute);
        nodeToAdd.Attributes.Append(timesseenAttribute);
        nodeToAdd = doc.SelectSingleNode("googletrends").AppendChild(nodeToAdd);

      }
      else
      {
        nodeToAdd.Attributes["lastseen"].Value = DateTime.Now.ToString("dd.MM.yyyy HH:mm");
        int currentTimeSeen = int.Parse(nodeToAdd.Attributes["timesseen"].Value);
        int newTimesSeen = currentTimeSeen + 1;
        nodeToAdd.Attributes["timesseen"].Value = newTimesSeen.ToString();
      }

      doc.Save("TrendWords.xml");
    }
    catch (Exception)
    {


    }

    //cd[@country='UK']
  }

  public static bool CheckKeyWordAllowed(string keyword)
  {
    bool result = true;
    if (string.IsNullOrEmpty(keyword))
    {
      return false;
    }
    Dictionary<string, string> forbiddenWords = GetForBiddenWords();
    foreach (KeyValuePair<string, string> wordItem in forbiddenWords)
    {
      if (keyword.ToLower().Contains(wordItem.Key))
      {
        result = false;
        break;
      }
    }
    return result;
  }

  private static Dictionary<string, string> GetForBiddenWords()
  {
    Dictionary<string, string> result = new Dictionary<string, string>();

    #region adult
    result.Add("erotic", "1");
    result.Add("sex", "1");
    result.Add("porn", "1");
    result.Add("adult", "1");
    result.Add("blowjob", "1");
    result.Add("bukkake", "1");
    result.Add("cum", "1");
    result.Add("threesome", "1");
    result.Add("vagina", "1");
    result.Add("naked", "1");
    result.Add("nude", "1");
    result.Add("penis", "1");
    result.Add("dick", "1");
    result.Add("nudity", "1");
    result.Add("tits", "1");
    result.Add("anal", "1");
    result.Add("anus", "1");
    result.Add("licking", "1");
    result.Add("hardcore", "1");
    result.Add("lesbian", "1");
    result.Add("oral", "1");
    result.Add("suck", "1");
    result.Add("imagefap", "1");
    result.Add("playboy", "1");
    result.Add("gay", "1");
    result.Add("vagnia", "1");
    result.Add("sloppy", "1");
    result.Add("arrse", "1");
    result.Add("arse", "1");
    result.Add("ass", "1");
    result.Add("b00bs", "1");
    result.Add("ballbag", "1");
    result.Add("butt", "1");
    result.Add("cock", "1");
    result.Add("sucker", "1");
    result.Add("69", "1");
    result.Add("bondage", "1");
    result.Add("defecation", "1");
    result.Add("fetish", "1");
    result.Add("genital", "1");
    result.Add("masturbation", "1");
    result.Add("pervert", "1");
    result.Add("sadomasochism", "1");
    result.Add("queer", "1");
    result.Add("semen", "1");
    result.Add("spanking", "1");
    result.Add("transvestite", "1");
    result.Add("submissive", "1");
    result.Add("urination", "1");
    result.Add("cunt", "1");
    result.Add("cyalis", "1");
    result.Add("fuck", "1");
    result.Add("scrotum", "1");
    result.Add("shit", "1");
    result.Add("slut", "1");
    result.Add("titt", "1");
    result.Add("wank", "1");
    result.Add("nigger", "1");
    result.Add("whore", "1");
    result.Add("Voyeur", "1");
    result.Add("preteen", "1");
    result.Add("lolita", "1");
    result.Add("xxl", "1");

    //result.Add("nigger","1");
    //result.Add("nigger","1");
    //result.Add("nigger","1");
    //result.Add("nigger","1");
    //result.Add("nigger","1");
    #endregion
    #region other
    result.Add(".com", "1");
    result.Add(".net", "1");
    result.Add("www.", "1");
    result.Add(":", "1");
    //result.Add("Voyeur","1");
    //result.Add("nigger","1");
    //result.Add("nigger","1");
    //result.Add("nigger","1");
    //result.Add("nigger","1");
    #endregion





    return result;
  }

  public static List<RssItem> GetNewsItems(string Keyword)
  {
    List<RssItem> result = new List<RssItem>();
    XmlDocument doc = new XmlDocument();
    string xmlPath;
    xmlPath = GetGoogleNewsXmlPath(Keyword);

    doc.Load(xmlPath);
    foreach (XmlNode nodeItem in doc.SelectNodes("/rss/channel/item[position()<7]"))
    {
      RssItem itemToAdd = new RssItem();
      itemToAdd.Content = nodeItem.SelectSingleNode("description").InnerText;
      itemToAdd.LinkUrl = nodeItem.SelectSingleNode("link").InnerText;

      //itemToAdd.LinkUrl = GetOriginalUrl(itemToAdd.LinkUrl);
      itemToAdd.Content = RemoveHTML(itemToAdd.Content);
      itemToAdd.Title = nodeItem.SelectSingleNode("title").InnerText;
      result.Add(itemToAdd);
    }
    return result;
  }

  private static string GetGoogleNewsXmlPath(string Keyword)
  {
    Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
    string folderName = "xmls";
    string xmlFileName = Keyword + "_" + DateTime.Now.Date.Year.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Day + "_" + DateTime.Now.Hour.ToString() + "_" + "googlenews" + ".xml";
    string fullPath = Path.Combine(folderName, xmlFileName);
    if (!Directory.Exists(folderName))
    {
      Directory.CreateDirectory(folderName);
    }
    if (!File.Exists(fullPath))
    {
      XmlDocument doc = new XmlDocument();
      doc.Load(string.Format(GoogleNewsFeedUrl, Keyword));
      doc.Save(fullPath);
    }
    return fullPath;
  }




  private static string GetOriginalUrl(string googeNewsLinkUrl)
  {
    int indexOfUrl = googeNewsLinkUrl.IndexOf(@"&url=");
    int indexOfei = googeNewsLinkUrl.IndexOf(@"&ei=");
    int indexOfcid = googeNewsLinkUrl.IndexOf(@"&cid=");
    int endIndex = 0;
    if (indexOfei > -1 && indexOfei < indexOfcid)
    {
      endIndex = indexOfei;
    }
    else
    {
      endIndex = indexOfcid;
    }
    string result = googeNewsLinkUrl.Substring(indexOfUrl + 5, endIndex);
    result = HttpUtility.UrlDecode(result);
    return result;
  }

  public static string RemoveHTML(string in_HTML)
  {
    string result;
    result = in_HTML;
    result = result.Replace("\r", string.Empty);
    result = result.Replace("\n", string.Empty);
    result = result.Replace("\t", string.Empty);
    result = result.Replace("&nbsp;", string.Empty);
    result = Regex.Replace(result, "<(.|\n)*?>", "", RegexOptions.IgnoreCase);
    //result = StripHTML(in_HTML);
    return result;

  }

  public static void AddToSearchArchive(string allowedWord,HttpServerUtility server,string ipAddress)
  {
    try
    {
      allowedWord = allowedWord.ToLower();
      //Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
      XmlDocument doc = new XmlDocument();
      doc.Load(server.MapPath("~/SearchArchive.xml"));
      XmlNode nodeToAdd = doc.SelectSingleNode("//search[@keyword='" + allowedWord + "']");
      if (nodeToAdd == null)
      {
        nodeToAdd = doc.CreateNode("element", "search", null);
        XmlAttribute keywordAttribute = doc.CreateAttribute("keyword");
        keywordAttribute.Value = allowedWord;
        XmlAttribute lastseenAttribute = doc.CreateAttribute("lastseen");

        lastseenAttribute.Value = DateTime.Now.ToString("dd.MM.yyyy HH:mm");
        XmlAttribute firstseenAttribute = doc.CreateAttribute("firstseen");
        firstseenAttribute.Value = DateTime.Now.ToString("dd.MM.yyyy HH:mm");
        XmlAttribute timesseenAttribute = doc.CreateAttribute("timesseen");
        timesseenAttribute.Value = "1";
        XmlAttribute ipAddressAtt = doc.CreateAttribute("ipAddress");
        ipAddressAtt.Value = ipAddress;

        nodeToAdd.Attributes.Append(keywordAttribute);
        nodeToAdd.Attributes.Append(firstseenAttribute);
        nodeToAdd.Attributes.Append(lastseenAttribute);
        nodeToAdd.Attributes.Append(timesseenAttribute);
        nodeToAdd.Attributes.Append(ipAddressAtt);
        nodeToAdd = doc.SelectSingleNode("searches").AppendChild(nodeToAdd);

      }
      else
      {
        nodeToAdd.Attributes["lastseen"].Value = DateTime.Now.ToString("dd.MM.yyyy HH:mm");
        int currentTimeSeen = int.Parse(nodeToAdd.Attributes["timesseen"].Value);
        int newTimesSeen = currentTimeSeen + 1;
        nodeToAdd.Attributes["timesseen"].Value = newTimesSeen.ToString();
      }

      doc.Save("SearchArchive.xml");
    }
    catch (Exception ex)
    {

        Exception exc=new Exception(AppDomain.CurrentDomain.BaseDirectory,ex);
        throw ex;
    }


  }


}